import {Button, Space, Table, Tooltip, Modal, Form, Input, message} from "antd";
import * as React from "react";
import {timeFormat} from "../../../utils/timeUtils";
import {CategoryAdd, PageCategory, CategoryDel} from '../../../api/admin/category';
import loading from "../../../commons/loading";



export default class AdminCategory extends React.Component{

    state = {
        data: [],
        searchName: '',
        total: 0,
        pageTotal: 0,
        pagination: {
            page: 1,
            size: 10
        },
        loading: false,
        isModalVisible: false,
        modelTitle: '增加分类',
        formData: {
            title: '',
            brief: ''
        },
        selectIds: []
    }

    formRef = React.createRef()

    async componentDidMount() {
        this.loadCategoryData()
    }

    openCategory = (type, itemData) => {

        this.setState({isModalVisible: true, modelTitle: type ? '增加分类' : '编辑分类'})
    }

    // 更新
    updateBtn = (recode) => {
        console.log(recode);
    }

    // 删除
    deleteBtn = (recode) => {
        CategoryDel({ids: recode.id}).then(res => {
            console.log("deleteCategory", res);
            if (res.code === "001001200") {
                message.success(res.data);
                this.loadCategoryData()
            } else {
                message.error(res.data);
            }
        }).catch(err => {
            message.error("删除数据失败");
        })
    }


    // 加载数据
    loadCategoryData = () => {
        const mask = loading();
        const {searchName, pagination} = this.state
        PageCategory({
            page: pagination.page,
            size: pagination.size,
            title: searchName
        }).then(res => {
            mask.close()
            console.log(res)
            if (res.code === "001001200") {
                const data = res.data
                console.log(data)
                this.setState({data: data.data})
                this.setState({total: data.total})
                this.setState({pageTotal: data.pageTotal})
            }

        }).catch(err => {
            mask.close()
            console.log(err);
        })
    }

    /**
     * 获取table选择框内容
     * @param selectedRowKeys
     */
    tabsOnChange = (selectedRowKeys) => {
        this.setState({selectIds: selectedRowKeys})
    }

    /**
     * 删除分类信息
     */
    deleteCategory = () => {
        const {selectIds} = this.state;
        CategoryDel({ids: selectIds.join(",")}).then(res => {
            console.log("deleteCategory", res);
            if (res.code === "001001200") {
                message.success(res.data);
                this.loadCategoryData()
            } else {
                message.error(res.data);
            }
        }).catch(err => {
            message.error("删除数据失败");
        })
    }

    /**
     * 打开模态框
     */
    openModel = async () => {
        const form = this.formRef.current
        try {
            const values = await form.validateFields(['title','brief'])
            CategoryAdd(values).then(res => {
                if (res.code === "001001200") {
                    message.success(res.data);
                    this.setState({isModalVisible: false})
                    this.loadCategoryData()
                    form.resetFields();
                } else {
                    message.error(res.data);
                }
            }).catch(err => {
            })
        } catch (err) {}
    }

    closeModel = () => {
        this.setState({isModalVisible: false})
    }




    render() {
        const {data, pagination, loading, isModalVisible, modelTitle, formData} = this.state;

        const columns = [
            {
                title: '分类名称',
                dataIndex: 'title',
                sorter: true,
                key: 'title'
            },
            {
                title: '图标',
                dataIndex: 'icon',
                key: 'icon'
            },
            {
                title: '文章数',
                dataIndex: 'sortNum',
                sorter: true,
                key: 'sortNum'
            },
            {
                title: '更新时间',
                dataIndex: 'CreateTime',
                sorter: true,
                key: 'CreateTime',
                render: CreateTime => (
                    <div>
                        {timeFormat(CreateTime)}
                    </div>
                )
            },
            {
                title: '备注',
                dataIndex: 'brief',
                key: 'brief',
                ellipsis: {
                    showTitle: false,
                },
                render: brief => (
                    <Tooltip placement="topLeft" title={brief}>
                        {brief}
                    </Tooltip>
                )
            },
            {
                title: '操作',
                dataIndex: '',
                key: 'options',
                render: (text, recode) => (
                    <Space size="small">
                        <Button type="primary" size="small" onClick={() => this.openCategory(false, recode)}>修改</Button>
                        <Button type="primary" size="small" onClick={() => this.deleteBtn(recode)} danger>删除</Button>
                        <Button type="primary" size="small" style={{borderColor: '#ffc53d', backgroundColor: '#ffc53d'}}>查看文章</Button>
                    </Space>
                )
            }
        ]

        const layout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 20 },
        };

        const onFinish = (values) => {
            console.log('Success:', values);
        };

        const onFinishFailed = (errorInfo) => {
            console.log('Failed:', errorInfo);
        };

        return (
            <div>
                <Space align="center" style={{marginBottom: 0.5 + 'rem'}}>
                    <Button type="primary" size="small" onClick={() => this.openCategory(true, null)}>增加分类</Button>
                    <Button type="primary" size="small" danger onClick={this.deleteCategory}>批量删除</Button>
                    <Button type="primary" size="small" style={{backgroundColor: '#73d13d', borderColor: '#73d13d'}} danger onClick={this.loadCategoryData}>刷新</Button>
                </Space>
                <Table
                    rowSelection={{onChange: this.tabsOnChange}}
                    size="middle"
                    columns={columns}
                    dataSource={data}
                    rowKey={record => record.id}
                    paginstion={pagination}
                    loading={loading}
                    bordered />
                <Modal
                    onOk={this.openModel}
                    onCancel={this.closeModel}
                    title={modelTitle}
                    visible={isModalVisible}>
                    <Form
                        ref={this.formRef}
                        {...layout}
                        name="basic"
                        initialValues={{ remember: true }}
                        onFinish={onFinish}
                        onFinishFailed={onFinishFailed}>
                        <Form.Item
                            initialValue={formData.title}
                            label="分类名称"
                            name="title"
                            rules={[{ required: true, message: '情输入正确的分类名称!' }]}>
                            <Input />
                        </Form.Item>
                        <Form.Item
                            initialValue={formData.brief}
                            label="分类备注"
                            name="brief">
                            <Input.TextArea rows={3} />
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        )
    }
}